package com.junjie.checkin.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.junjie.checkin.entity.Enum.StudentGiftStatusEnum;
import com.junjie.checkin.entity.TGift;
import com.junjie.checkin.entity.TStudentActivityHistory;
import com.junjie.checkin.entity.TStudentGift;
import com.junjie.checkin.entity.TUser;
import com.junjie.checkin.exception.ResourceNotFountException;
import com.junjie.checkin.mapper.GiftMapper;
import com.junjie.checkin.mapper.StudentGiftMapper;
import com.junjie.checkin.mapper.UserMapper;
import com.junjie.checkin.request.gift.GiftOrderPageRequest;
import com.junjie.checkin.response.PageResult;
import com.junjie.checkin.response.admin.AdminGiftOrderResponse;
import com.junjie.checkin.response.admin.OrderPageResult;
import com.junjie.checkin.response.front.GiftOrderResponse;
import com.junjie.checkin.security.service.JwtService;
import com.junjie.checkin.security.service.impl.JwtServiceImpl;
import com.junjie.checkin.utils.DateTimeFormat;
import com.junjie.checkin.websocket.entity.StompMessage;
import com.junjie.checkin.websocket.manger.WebSocketSessionManager;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author 洪浚杰
 * @description 礼品订单服务
 * @date 2025/6/18 16:45
 */
@Service
public class StudentGiftService {
    @Autowired
    WebSocketSessionManager webSocketSessionManager;

    @Autowired
    GiftMapper giftMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    StudentGiftMapper studentGiftMapper;
    @Autowired
    JwtServiceImpl jwtService;
    @Autowired
    SimpMessagingTemplate simpMessagingTemplate;
    /**
     * 获取礼物兑换记录
     * @param id 礼物id
     * @param pageRequest 分页参数
     */
    public OrderPageResult<AdminGiftOrderResponse> getGiftOrderByGiftId(Integer id, GiftOrderPageRequest pageRequest) {
        TGift gift = giftMapper.selectById(id);
        if (Objects.isNull(gift)){
            throw new ResourceNotFountException();
        }
        pageRequest.initDefault();
        PageHelper.startPage(pageRequest.getPage(),pageRequest.getPageSize());
        Page<TStudentGift> page = studentGiftMapper.pageQueryGiftOrder(id, pageRequest.getKeyword());
//        System.out.println(page.getResult());
        List<AdminGiftOrderResponse> list = page.getResult().stream().map(order -> {
            AdminGiftOrderResponse response = new AdminGiftOrderResponse();
            BeanUtils.copyProperties(order, response);
            response.setScore(order.getPoint());
            return response;
        }).toList();
        Long distributedCount = studentGiftMapper.selectDistributedCount(gift.getId());
        return new OrderPageResult<AdminGiftOrderResponse>(page.getTotal(), list, distributedCount,page.getTotal()-distributedCount);
    }

    /**
     * 修改订单状态
     * @param id 订单id
     * @param status 订单状态
     * @param token 令牌
     */
    public void updateOrderStatus(Integer id, StudentGiftStatusEnum status, String token) {
        TStudentGift studentGift = studentGiftMapper.selectById(id);
        if (Objects.isNull(studentGift)){
            throw new ResourceNotFountException();
        }
        studentGift.setStatus(status);
        studentGift.setUpdateBy(jwtService.analyzeToken(token).getUsername());
        // 当订单成功时，将提示用户领取成功
        if (status == StudentGiftStatusEnum.SUCCESS){
            TUser user = userMapper.selectById(studentGift.getUserId());
            String username = studentGift.getStudentId();
            System.out.println("目标用户: " + username);
            System.out.println("活跃会话: " + webSocketSessionManager.getSessionId(username));
            StompMessage stompMessage = new StompMessage<>("giftExchangeSuccess","礼品已送达",null);
            simpMessagingTemplate.convertAndSendToUser(studentGift.getStudentId(),"/queue/gift", stompMessage);
        }
        studentGiftMapper.updateById(studentGift);
    }

    /**
     * 获取用户的礼物订单列表
     * @param token 用户令牌
     * @param pageRequest 分页参数
     * @return
     */

    public PageResult<GiftOrderResponse> getGiftOrderList(String token, GiftOrderPageRequest pageRequest) {
        pageRequest.initDefault();
        Integer id = jwtService.analyzeToken(token).getUser().getId();
        PageHelper.startPage(pageRequest.getPage(),pageRequest.getPageSize());
        Page<TStudentGift> page = studentGiftMapper.pageQueryGiftOrderByUserId(id, pageRequest.getKeyword());
        List<GiftOrderResponse> list = page.getResult().stream().map(order -> {
            GiftOrderResponse response = new GiftOrderResponse();
            BeanUtils.copyProperties(order, response);
            response.setPoint(-order.getPoint());
            response.setCreateTime(DateTimeFormat.dateToString(order.getCreateTime()));
            return response;
        }).toList();
        return new PageResult<>(page.getTotal(), list);
    }
}
